<template>
  <div>
    <div class="code-box">
        <section class="code-box-demo">
        <div>
            <slot name="code"></slot>
        </div>
        </section>
        <section class="code-box-meta markdown">
        <h4>{{desName}}</h4>
        <div class="code-box-des">
            <slot name="des"></slot>
        </div>
        <div class="code-box-actions">
            <div class="code-box-btn" @click="copy()"><a-icon type="copy" />复制代码</div>
            <div class="code-box-btn" @click="toggle(fold)"><a-icon type="swap" />查看代码</div>
        </div>
        </section>
        <section class="highlight-wrapper" v-show="fold == true">
            <v-md-editor v-model="val" height="800px" @change="change" v-show="show == true"></v-md-editor>
            <div v-html="md"></div>
            <a-button type="primary" @click="exportMd" style="margin:10px;" v-show="show == true">导出</a-button>
        </section>
    </div>
    
  </div>
</template>

<script>
import marked from 'marked'
import prism from "prismjs";

export default {
    props: {
        show: {
            type: Boolean,
            default: false
        },
        val: {
            type: String,
            default: ''
        },
        desName: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            md: null,
            fold: false,
        }
    },
    methods: {
        change() {
            let reg = new RegExp("<pre", "g");
            let content = this.md = marked(this.val);
            let str = content.replace(reg, `<pre class="line-numbers"`);
            this.md = str;
            setTimeout(() => {
                prism.highlightAll();
            }, 0);
        },
        toggle(fold) {
            this.fold = !this.fold
        },
        exportMd() {
            console.log(marked(this.val));
        },
        copy() {
            this.$copyText(marked.lexer(this.val)[0].text).then(
                e=>{
                    console.log('复制成功：', e.text);
                    this.$message.success('复制成功');
                },
                e=>{
                    console.log('复制失败：', e);
                }
            )
        }
    }
}
</script>

<style lang="less" scoped>

</style>